package modelo;

public class EndControle extends Thread {
	private int entrada[] = new int[32];
	private int saida[] = new int[32];
	private int linhaDeControle = 0;
	private SMailbox canalEntrada = new SMailbox();
	private SMailbox canalSaidaEnd = new SMailbox();
	private SMailbox canalSaidaDados = new SMailbox();
	private SMailbox canalControle = new SMailbox();
	
	public EndControle(SMailbox canalEntrada, SMailbox canalSaidaEnd, SMailbox canalSaidaDados, SMailbox canalControle){
		this.canalEntrada = canalEntrada;
		this.canalSaidaEnd = canalSaidaEnd;
		this.canalSaidaDados = canalSaidaDados;
		this.canalControle = canalControle;
	}	
	public void atualizacao(){
		if(linhaDeControle==1){
			saida=entrada;
		}
	}
	public void run(){
		entrada = (int[]) canalEntrada.receive();
		while(linhaDeControle==0){
			linhaDeControle = (Integer) canalControle.receive();
		}
		atualizacao();
		int end[] = new int[10];
		int dados[] = new int[22];
		for(int i=0;i<10;i++){
			end[i]=saida[i];
		}
		for(int i=10; i<32; i++){
			dados[i]=saida[i];
		}
		if(converteDecimal(end)!=1023){
			canalSaidaEnd.send(end);
		}
		canalSaidaDados.send(dados);
    }
	public int converteDecimal(int b[]){
		int dec, i, z=0;
		dec = 0;
		i=0;
		int bin[] = new int[16];
		for(i=0; i<16; i++){
			bin[i]=b[i];
		}
		if(bin[0]==1){
			for(i=1; i<16; i++){
				if(z==1){
					if(bin[16-i]==0){
						bin[16-i]=1;
					}
					else{
						bin[16-i]=0;
					}
				}else if(bin[16-i]==1){
					z=1;
				}
			}
		}
		for(i=1; i<16; i++){
			if(bin[16-i]==1){
				dec += Math.pow(2,i-1);
			}
		}
		if(bin[0]==1){
			if(dec==0){
				dec+=Math.pow(2,16)/2;
			}
			dec*=-1;
		}
		return dec;
	}
}
